package org.hw.controller.guyang;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hw.entity.User;
import org.hw.service.UserService;
import org.hw.util.PageObject;
import org.hw.util.ResultData;
import org.hw.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.LinkedHashMap;
import java.util.UUID;

import static org.hw.util.MD5Tool.md5;

@Slf4j
@Validated
@RestController
//@RequestMapping("/login")
public class LoginController {


    @Autowired
    UserService userService;
    @Autowired
    private RedisUtil redisUtil;

    @PostMapping("/login")
    @ApiOperation("用户登录")
    @ResponseBody
    @Transactional
    ResultData<User> add(@Validated @RequestBody User user) {
        // 检查用户名和密码是否为空
        if (user.getUserName() == null || user.getUserName().isEmpty() || user.getPassWord() == null || user.getPassWord().isEmpty()) {
            return ResultData.fail("用户名和密码不能为空");
        }

        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("userName", user.getUserName());
        qw.eq("passWord", md5(user.getPassWord()));

        User loginUser = userService.getOne(qw);

        // 检查查询结果
        if (loginUser == null) {
            return ResultData.fail("用户名或密码错误");
        }

        // 生成 token
        String token = UUID.randomUUID().toString();
        // 将用户信息存入 LinkedHashMap
        LinkedHashMap<String, Object> hashMap = new LinkedHashMap<>();
        hashMap.put("unitId", loginUser.getUnitId());
        hashMap.put("userId", loginUser.getId());
        hashMap.put("userName", loginUser.getUserName());
        hashMap.put("id", loginUser.getId());
        hashMap.put("address", loginUser.getAddress());
        hashMap.put("createTime", System.currentTimeMillis());

        // 将用户信息存入 Redis
        System.out.println("hashMap+hashMap");
        System.out.println(hashMap);
        System.out.println(token);
        redisUtil.set("session_" + token, hashMap);

        // 返回包含 token 的登录成功信息
        loginUser.setPassWord(token);
        // 返回包含 token 的登录成功信息
        return ResultData.success(loginUser);
    }
    @GetMapping("/login")
    @ApiOperation("用户登录")
    @ResponseBody
    @Transactional
    ResultData test() {
        return ResultData.success("登录成功信息");
    }

    // 新增注册接口
    @PostMapping("/register")
    @ApiOperation("用户注册")
    @ResponseBody
    @Transactional
    ResultData<User> register(@Validated @RequestBody User user) {
        // 检查用户名和密码是否为空
        if (user.getUserName() == null || user.getUserName().isEmpty() || user.getPassWord() == null || user.getPassWord().isEmpty()) {
            return ResultData.fail("用户名和密码不能为空");
        }

        // 检查用户名是否已存在
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("userName", user.getUserName());
        if (userService.getOne(qw) != null) {
            return ResultData.fail("用户名已存在");
        }

        // 对密码进行 MD5 加密
        user.setPassWord(md5(user.getPassWord()));

        // 保存用户信息
        boolean saveResult = userService.save(user);
        if (saveResult) {
            return ResultData.success(user);
        } else {
            return ResultData.fail("注册失败");
        }
    }

    // 新增修改用户信息接口
    @PutMapping("/user/update")
    @ApiOperation("修改用户信息")
    @ResponseBody
    @Transactional
    ResultData<User> updateUser(@Validated @RequestBody User user) {
        // 检查用户 ID 是否为空
        if (user.getId() == null) {
            return ResultData.fail("用户 ID 不能为空");
        }

        // 检查用户是否存在
        User existingUser = userService.getById(user.getId());
        if (existingUser == null) {
            return ResultData.fail("用户不存在");
        }

        // 禁止修改用户名
        if (user.getUserName() != null && !user.getUserName().equals(existingUser.getUserName())) {
            return ResultData.fail("不允许修改用户名");
        }

        // 手动更新其他字段
        if (user.getOpenId() != null) existingUser.setOpenId(user.getOpenId());
        if (user.getPhoto() != null) existingUser.setPhoto(user.getPhoto());
        if (user.getPassWord() != null) existingUser.setPassWord(md5(user.getPassWord()));
        if (user.getNickName() != null) existingUser.setNickName(user.getNickName());
        if (user.getName() != null) existingUser.setName(user.getName());
        if (user.getSex() != null) existingUser.setSex(user.getSex());
        if (user.getPhone() != null) existingUser.setPhone(user.getPhone());
        if (user.getIDCard() != null) existingUser.setIDCard(user.getIDCard());
        if (user.getBrisday() != null) existingUser.setBrisday(user.getBrisday());
        if (user.getAddress() != null) existingUser.setAddress(user.getAddress());
        if (user.getStatus() != null) existingUser.setStatus(user.getStatus());
        if (user.getSource() != null) existingUser.setSource(user.getSource());
        if (user.getDept() != null) existingUser.setDept(user.getDept());
        if (user.getWxNotify() != null) existingUser.setWxNotify(user.getWxNotify());
        if (user.getEnterpriceId() != null) existingUser.setEnterpriceId(user.getEnterpriceId());

        // 更新用户信息
        boolean updateResult = userService.updateById(existingUser);
        if (updateResult) {
            return ResultData.success(userService.getById(user.getId()));
        } else {
            return ResultData.fail("修改用户信息失败");
        }
    }
}
